package com.example.demo.controller;

import com.example.demo.service.VerificationCodeService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

@RestController
@RequestMapping("/user")
public class Login2Controller {

    @Autowired
    private VerificationCodeService verificationCodeService;

    // 记录连续登录失败次数的Map，键为手机号，值为失败次数
    private Map<String, Integer> failedLoginAttempts = new HashMap<>();

    // 验证验证码接口
    @RequestMapping(value = "/login2", method = RequestMethod.POST)
    public ResponseEntity<Map<String, Object>> verifyCode(@RequestBody Map<String, String> requestBody) {
        Map<String, Object> response = new HashMap<>();

        // 获取请求参数中的手机号码和验证码类型
        String phoneNumber = requestBody.get("phoneNumber");
        String codeType = "verificationCode1"; // 假设要验证的验证码类型是verificationCode1
        String code = requestBody.get(codeType);

        // 检查用户是否连续登录失败3次，如果是，则锁定账户5分钟
        if (failedLoginAttempts.containsKey(phoneNumber) && failedLoginAttempts.get(phoneNumber) >= 3) {
            response.put("code", 401); // 401表示未授权，即账户被锁定
            response.put("message", "多次登录失败，账户锁定");
            return ResponseEntity.status(401).body(response);
        }

        // 使用VerificationCodeService验证验证码
        boolean isCodeValid = verificationCodeService.verifyCode(phoneNumber, codeType, code);

        if (isCodeValid) {
            // 登录成功，重置失败次数
            failedLoginAttempts.remove(phoneNumber);
            response.put("code", 200);
            response.put("message", "登录成功");
        } else {
            // 登录失败，增加失败次数，并提示失败原因
            failedLoginAttempts.put(phoneNumber, failedLoginAttempts.getOrDefault(phoneNumber, 0) + 1);
            if (failedLoginAttempts.get(phoneNumber) >= 3) {
                // 如果连续登录失败3次，记录并设置锁定时间
                response.put("code", 401);
                response.put("message", "多次登录失败，账户锁定，请5分钟后再试");
                failedLoginAttempts.put(phoneNumber, 3); // 防止继续增加失败次数
                // 设置定时任务，在5分钟后解除锁定
                new java.util.Timer().schedule(
                        new java.util.TimerTask() {
                            @Override
                            public void run() {
                                failedLoginAttempts.remove(phoneNumber);
                            }
                        },
                        TimeUnit.MINUTES.toMillis(5)
                );
            } else {
                // 如果失败次数未达到3次，提示验证码错误
                response.put("code", 400);
                response.put("message", "验证码错误，登录失败");
            }
        }

        // 返回验证结果
        return ResponseEntity.ok(response);
    }
}

